/*  
 *  Copyright RobOtter (2008) 
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/** \file compass.c
  *
  * Manage communication with the electronic compasss via I2C
  */

#include "compass.h"

#include <aversive/wait.h>

#include "macro_maths.h"
#include "i2cm.h"

void compass_init()
{
  // Initialize I2C 
  // (in case it's not the first time the
  // current i2c communication will be lost)
  i2cm_init();

  // The compass seems to take some time to initialize
  wait_ms(500);
}

uint16_t compass_getBearing_deg()
{
  uint8_t buffer;
  uint16_t angle;
  uint8_t rv;
  
  buffer = COMPASS_16BIT_BEARING_LSB;
  // Send register number 
  i2cm_send(COMPASS_I2C_ADDRESS,1,&buffer);
  // Receive register value
  rv = i2cm_rcv_single(COMPASS_I2C_ADDRESS);
  
  angle = rv;

  buffer = COMPASS_16BIT_BEARING_MSB;
  // Send register number 
  i2cm_send(COMPASS_I2C_ADDRESS,1,&buffer);
  // Receive register value
  rv = i2cm_rcv_single(COMPASS_I2C_ADDRESS);

  angle |= rv <<8;

  return angle;
}

double compass_getBearing_rad()
{
  double angle;

  angle = compass_getBearing_deg();
  angle /= 10;
  angle = DEG2RAD(angle);

  return angle;
}
